package com.heifeng.cloudshelf.mvp.main.activity;

import android.Manifest;
import android.app.Activity;
import android.content.IntentFilter;
import android.os.Handler;
import androidx.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.heifeng.cloudshelf.NetWorkReceiver;
import com.heifeng.cloudshelf.R;
import com.heifeng.cloudshelf.base.BaseActivity;
import com.heifeng.cloudshelf.base.BaseResponse;
import com.heifeng.cloudshelf.constants.HTTPConstants;
import com.heifeng.cloudshelf.event.PushEvent;
import com.heifeng.cloudshelf.mvp.main.contract.MainActivityContract;
import com.heifeng.cloudshelf.mvp.main.presenter.MainActivityPresenter;
import com.heifeng.cloudshelf.mvp.product.activity.ProductActivity;
import com.heifeng.cloudshelf.mvp.programme.activity.ProgrammeActivity;
import com.heifeng.cloudshelf.mvp.search.activity.SearchHomeActivity;
import com.heifeng.cloudshelf.mvp.show.activity.ShowHomeActivity;
import com.heifeng.cloudshelf.push.JpushUtils;
import com.heifeng.cloudshelf.utils.PermissionsUtils;
import com.heifeng.cloudshelf.utils.ToastUitl;
import com.heifeng.cloudshelf.widget.AppDialog;
import com.heifeng.cloudshelf.widget.CustomVideoPlayer;
import com.heifeng.cloudshelf.widget.JZMediaExo;
import com.orhanobut.hawk.Hawk;
import com.youth.banner.Banner;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jzvd.Jzvd;

public class MainActivity extends BaseActivity<MainActivityPresenter> implements MainActivityContract.View {

    @BindView(R.id.banner)
    Banner banner;

    @BindView(R.id.videoplayer)
    CustomVideoPlayer videoPlayer;

    @BindView(R.id.iv_bg)
    ImageView ivBg;

    @BindView(R.id.iv_product)
    ImageView ivProduct;

    @BindView(R.id.iv_image_bg)
    ImageView iv_image_bg;

    @BindView(R.id.iv_idea)
    ImageView ivIdea;

    @BindView(R.id.iv_search)
    ImageView ivSearch;

    @BindView(R.id.iv_share_home)
    ImageView ivShare;

    @BindView(R.id.tv_logout)
    View tv_logout;

    @BindView(R.id.l_had_video_code)
    LinearLayout lHadVideoCode;//有视频时的菊花码

    @BindView(R.id.l_no_video_code)
    LinearLayout lNoVideoCode;//没有视频时的菊花码

    private boolean isPermissions = false;
    private boolean isClicked = false;


//    private Bitmap bitmap;
//    private Bitmap bmp;

//    private String imageUrl;
    private NetWorkReceiver netWorkReceiver;

    //如果设置了target > 28，需要增加这个权限，否则不会弹出"始终允许"这个选择框
//    private static String BACKGROUND_LOCATION_PERMISSION = "android.permission.ACCESS_BACKGROUND_LOCATION";

    /**
     * 需要进行检测的权限数组
     */

    protected String[] needPermissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
    };

    //    protected String[] needPermissions = {
//            Manifest.permission.ACCESS_COARSE_LOCATION,
//            Manifest.permission.ACCESS_FINE_LOCATION,
//            Manifest.permission.WRITE_EXTERNAL_STORAGE,
//            Manifest.permission.READ_EXTERNAL_STORAGE,
//            Manifest.permission.READ_PHONE_STATE
//    };
    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initEventAndData() {
//        mPresenter.UpdateFinishedDialog();
//        mPresenter.UpdateProgressDialog();

        startNet();

        PermissionsUtils.getInstance().chekPermissions(this, needPermissions, new PermissionsUtils.IPermissionsResult() {
            @Override
            public void passPermissons() {

            }

            @Override
            public void forbitPermissons() {

            }
        });


        EventBus.getDefault().register(this);
//        initPermissions();
//        startService(JPushMessageService.startServer(getApplicationContext()));
        JpushUtils.start(getApplicationContext());
        JpushUtils.setAlias(getApplicationContext(), HTTPConstants.macAddress);


        mPresenter.init();
        //图片设置高斯模糊
//        bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.banner);
//        bmp = FastBlur.doBlur(bitmap, 100, false);
//        ivBg.setImageBitmap(bmp);

        if (null != Hawk.get(HTTPConstants.PERMISSION_KEY)) {
            boolean isPermission = Hawk.get(HTTPConstants.PERMISSION_KEY);
            if (isPermission) {
                if (TextUtils.isEmpty(HTTPConstants.city)) {
                    mPresenter.gdLocation();
                }
            }
        }

        NetWorkReceiver.setOnNetConnectListener(isConnected -> {
            isClicked = false;
            setNetConnect(isConnected);
        });
    }

    private void startNet() {
        netWorkReceiver = new NetWorkReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.wifi.STATE_CHANGE");
        intentFilter.addAction("android.Net.wifi.WIFI_STATE_CHANGED");
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        registerReceiver(netWorkReceiver, intentFilter);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            android.os.Process.killProcess(android.os.Process.myPid());
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isClicked = false;
        setLoginOutView(HTTPConstants.isLogined);
        if (!HTTPConstants.isLogined) {
            mPresenter.ShowLoginDialog();
        }
        mPresenter.getAdvertising();
        mPresenter.checkUpdateApp();
    }

    //初始化权限
//    private void initPermissions() {
//        if (Build.VERSION.SDK_INT > 28
//                && getApplicationContext().getApplicationInfo().targetSdkVersion > 28) {
//            needPermissions = new String[]{
//                    Manifest.permission.ACCESS_COARSE_LOCATION,
//                    BACKGROUND_LOCATION_PERMISSION
////            needPermissions = new String[]{
////                    Manifest.permission.ACCESS_COARSE_LOCATION,
////                    Manifest.permission.ACCESS_FINE_LOCATION,
////                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
////                    Manifest.permission.READ_EXTERNAL_STORAGE,
////                    Manifest.permission.READ_PHONE_STATE,
////                    BACKGROUND_LOCATION_PERMISSION
//            };
//        }
//        if (Build.VERSION.SDK_INT >= 23
//                && getApplicationInfo().targetSdkVersion >= 23) {
//            PermissionsUtils.getInstance().chekPermissions(this, needPermissions, new PermissionsUtils.IPermissionsResult() {
//                @Override
//                public void passPermissons() {
//                    mPresenter.gdLocation();
//                }
//
//                @Override
//                public void forbitPermissons() {
//                    mPresenter.ShowLocationUnableDialog();
//                }
//            });
//        }
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        NetWorkReceiver.clearNetConnectListeners();
        unregisterReceiver(netWorkReceiver);
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionsUtils.getInstance().onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    public Banner getBanner() {
        return banner;
    }

    @Override
    public CustomVideoPlayer getPlayer() {
        return videoPlayer;
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Jzvd.releaseAllVideos();
        isClicked = false;
    }

    @Override
    public void setLoginOutView(boolean isVisibility) {
        HTTPConstants.isLogined = isVisibility;
        if (isVisibility) {
            tv_logout.setVisibility(View.VISIBLE);
        } else {
            tv_logout.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void setImageAndVideoData(String imageUrl, String videoUrl, String videoPic) {

        if (!TextUtils.isEmpty(imageUrl)) {
            Glide.with(this).load(imageUrl).into(iv_image_bg);
//            Glide.with(MainActivity.this).asBitmap().load(imageUrl).into(new SimpleTarget<Bitmap>() {
//                @Override
//                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
//                    iv_image_bg.setImageBitmap(resource);
////                    bmp = FastBlur.doBlur(bitmap, 100, false);
////                    ivBg.setImageBitmap(bmp);
//
//                }
//            });

//            if (TextUtils.isEmpty(this.imageUrl))
//                Glide.with(this).asBitmap().load(imageUrl).apply(RequestOptions.bitmapTransform(new BlurTransformation(this, 25))).into(ivBg);

//            this.imageUrl = imageUrl;
        }

        //设置视频播放源
        if (!TextUtils.isEmpty(videoUrl)) {
            Log.e("video", "url:" + videoUrl);
            videoPlayer.setVisibility(View.VISIBLE);
            videoPlayer.setUp(videoUrl, "", Jzvd.SCREEN_NORMAL, JZMediaExo.class);
            if (!TextUtils.isEmpty(videoPic)) {
                //设置视频预览图,预览图链接为空，则是黑色背景
                Glide.with(mContext).load(videoPic).apply(new RequestOptions().skipMemoryCache(true).error(R.mipmap.ic_video_default)).into(videoPlayer.thumbImageView);
            }
        } else {
            videoPlayer.setVisibility(View.GONE);
        }
    }

    @Override
    public boolean isGetPermissions() {
        return isPermissions;
    }

    @Override
    public void ToastVersion(boolean isNewVersion, String version) {
        if (isNewVersion) {
            runOnUiThread(() -> mPresenter.UpdateTipsDialog());
        }
    }

    @Override
    public boolean netConnect() {
        return isNetConnect();
    }

    @Override
    public void locationError() {
        runOnUiThread(() -> mPresenter.ShowLocationFaildDialog());
    }

    @Override
    public void toastCodeText(BaseResponse baseResponse) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (0 == baseResponse.getCode()) {
                        Toast toast = Toast.makeText(MainActivity.this, baseResponse.getmsg(), Toast.LENGTH_LONG);
                        toast.setGravity(Gravity.CENTER, 0, 0);
                        toast.show();
                        AppDialog.countTime(120);
                    } else {
                        Toast toast = Toast.makeText(MainActivity.this, baseResponse.getmsg(), Toast.LENGTH_LONG);
                        toast.setGravity(Gravity.CENTER, 0, 0);
                        toast.show();
                        if (600001 == baseResponse.getCode()) {
                            mPresenter.ShowTimeOverDialog(baseResponse.getmsg());
                        }
                    }
                }catch (Exception e){

                }
            }
        });
    }

    @Override
    public void animationEnd(int type) {
        switch (type) {
            case R.id.l_idea://方案库
                ProgrammeActivity.StartActivity(MainActivity.this, R.mipmap.ic_title_programee, getResources().getString(R.string.text_idea_library), 0);
                break;
            case R.id.l_product://产品大全
                ProductActivity.open(MainActivity.this);
                break;
            case R.id.l_search://搜搜我家
                SearchHomeActivity.open(MainActivity.this);
                break;
            case R.id.l_show://晒晒我家
                ShowHomeActivity.open(MainActivity.this);
                break;
        }
    }

    @Override
    public Activity getThisActivity() {
        return this;
    }

    //    PushEvent
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void PushEvent(PushEvent event) {
        AppDialog.OneButtonDialog(this, this.getResources().getString(R.string.text_time_over_tips), event.getPush().getContent(),
                this.getResources().getString(R.string.text_i_know), new AppDialog.OneButtonOnClickListener() {
                    @Override
                    public void onBtnClick() {
                        //ToastUitl.showLong("到期提示");
//                            ShowLoginDialog();
                    }
                }).showDialog();
    }


    @OnClick({R.id.tv_logout, R.id.l_idea, R.id.l_product, R.id.l_search, R.id.l_show})
    public void OnClick(View view) {
        checkNet();

        switch (view.getId()) {
            case R.id.tv_logout://退出账号
                mPresenter.ShowLogoutDialog();
                break;
            case R.id.l_idea://方案库

                if (isClicked) {
                    return;
                }
                isClicked = true;

                if (!isNetConnect()) {
                    ToastUitl.showLong("网络异常，请检查网络");
                    return;
                }
                mPresenter.ImageViewClickChange(ivIdea,R.id.l_idea);

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ProgrammeActivity.StartActivity(MainActivity.this, R.mipmap.ic_title_programee, getResources().getString(R.string.text_idea_library), 0);
                    }
                }, 200);    //延时

                break;
            case R.id.l_product://产品大全

                if (isClicked) {
                    return;
                }
                isClicked = true;

                if (!isNetConnect()) {
                    ToastUitl.showLong("网络异常，请检查网络");
                    return;
                }

                mPresenter.ImageViewClickChange(ivProduct,R.id.l_product);

                new Handler().postDelayed(() -> ProductActivity.open(MainActivity.this), 200);    //延时
                break;
            case R.id.l_search://搜搜我家

                if (isClicked) {
                    return;
                }
                isClicked = true;
                if (!isNetConnect()) {
                    ToastUitl.showLong("网络异常，请检查网络");
                    return;
                }

                mPresenter.ImageViewClickChange(ivSearch,R.id.l_search);

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        SearchHomeActivity.open(MainActivity.this);
                    }
                }, 200);    //延时

                break;
            case R.id.l_show://晒晒我家

                if (isClicked) {
                    return;
                }
                isClicked = true;
                if (!isNetConnect()) {
                    ToastUitl.showLong("网络异常，请检查网络");
                    return;
                }

                mPresenter.ImageViewClickChange(ivShare,R.id.l_show);

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ShowHomeActivity.open(MainActivity.this);
                    }
                }, 200);    //延时
                //mPresenter.ShowLoginDialog();
                break;
        }
    }

//    public Bitmap returnBitMap(final String url) {
//
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                URL imageurl = null;
//
//                try {
//                    imageurl = new URL(url);
//                } catch (MalformedURLException e) {
//                    e.printStackTrace();
//                }
//                try {
//                    HttpURLConnection conn = (HttpURLConnection) imageurl.openConnection();
//                    conn.setDoInput(true);
//                    conn.connect();
//                    InputStream is = conn.getInputStream();
//                    bitmap = BitmapFactory.decodeStream(is);
//                    is.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
//
//        return bitmap;
//    }

}
